package com.bit.talkoftoday;

import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

public class ScreenReceiver extends BroadcastReceiver {
	private KeyguardManager km = null;
	private KeyguardManager.KeyguardLock keyLock = null;

	private TelephonyManager telephonyManager = null;
	private boolean isPhoneIdle = true;

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub

		if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {

			if (telephonyManager == null) {
				telephonyManager = (TelephonyManager) context
						.getSystemService(Context.TELEPHONY_SERVICE);
				telephonyManager.listen(phoneListener,
						PhoneStateListener.LISTEN_CALL_STATE);
			}

			if (isPhoneIdle) {

				if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
					// if (km == null){
					// km = (KeyguardManager)
					// context.getSystemService(context.KEYGUARD_SERVICE);
					//
					// if (keyLock == null){
					// keyLock = km.newKeyguardLock(context.KEYGUARD_SERVICE);
					// }
					// }
					// disableKeyguard();
					ActivityManager am = (ActivityManager) context
							.getSystemService(context.ACTIVITY_SERVICE);
					List<ActivityManager.RunningTaskInfo> taskInfo = am
							.getRunningTasks(10);
					ComponentName componentInfo = null;
					for (RunningTaskInfo runningTaskInfo : taskInfo) {

						if (runningTaskInfo.topActivity.getClassName().equals(
								"com.bit.talkoftoday.LockScreenActivity")) {

							return;
						}
					}

					Intent i = new Intent(context, LockScreenActivity.class);
					i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(i);

				}
			}
		}
	}

	private PhoneStateListener phoneListener = new PhoneStateListener() {
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE:
				isPhoneIdle = true;
				break;
			case TelephonyManager.CALL_STATE_RINGING:
				isPhoneIdle = false;
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:
				isPhoneIdle = false;
				break;
			}
		}
	};

	public void reenableKeyguard() {
		keyLock.reenableKeyguard();
	}

	public void disableKeyguard() {
		keyLock.disableKeyguard();
	}

}
